<template>
  <basic-container>
    <div>
      <div class="echarts-border">
        <el-form ref="submitForm" label-width="80px" style="margin-left: 20px;display: flex">
          <el-form-item label="设计师:">
            <el-select id="id-creativereport-basicsreport-controlSubmitUserId"
                       multiple filterable v-model="submitTypeForm.userId" size="mini" style="margin-right: 20px" @change="controlSubmitUserId">
              <el-option v-for="(item,index) in submittedList" :key="index" :value="item.id"
                         :label="item.realName"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围:">
            <el-date-picker v-model="submitTypeForm.date"
                            id="id-creativereport-basicsreport-timeChange-two"
                            size="mini"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd"
                            :picker-options="pickerOption"
                            @change="timeChange($event,'submitType')"
            ></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <!--每日制作交及在线数-->
      <div class="echarts-border">
        <el-form ref="submitForm" label-width="80px" style="margin-left: 20px;display: flex">
        </el-form>
        <div id="submitNumCharts" :style="{width: '100%', height: '400px'}"></div>
      </div>
      <!--制作素材类型及数量统计-->
      <div class="echarts-border">
        <div style="font-weight: 800;font-size: 18px;margin-left: 5px;margin-bottom: 10px">制作素材类型及数量统计</div>
        <el-form ref="submitTypeForm" label-width="80px" style="margin-left: 20px;display: flex" >
        </el-form>
        <div>
          <div style="display: flex">
            <div id="StatisticsBar" :style="{width: '50%', height: '400px'}"></div>
            <div id="StatisticsPie" :style="{width: '50%', height: '400px'}"></div>
          </div>
          <div id="StatisticsLine" :style="{width: '100%', height: '400px'}"></div>
        </div>

      </div>
      <!--在线素材-->
<!--      <div class="echarts-border">-->
<!--        <div style="font-weight: 800;font-size: 18px;margin-left: 5px;margin-bottom: 10px">在线素材</div>-->
<!--        <el-form ref="onLineForm" label-width="80px" style="margin-left: 20px;display: flex">-->
<!--          <el-form-item label="制作人:">-->
<!--            <el-select v-model="onLineForm.userId" multiple multiple-limit="5" filterable @change="controlOnLineUserId" size="mini" style="margin-right: 20px">-->
<!--              <el-option v-for="(item,index) in submittedList" :key="index" :value="item.id"-->
<!--                         :label="item.realName"></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="时间范围:">-->
<!--            <el-date-picker v-model="onLineForm.date"-->
<!--                            size="mini"-->
<!--                            type="daterange"-->
<!--                            range-separator="至"-->
<!--                            start-placeholder="开始日期"-->
<!--                            end-placeholder="结束日期"-->
<!--                            format="yyyy-MM-dd"-->
<!--                            value-format="yyyy-MM-dd"-->
<!--                            :picker-options="pickerOption"-->
<!--                            @change="timeChange($event,'onLine')"-->
<!--            ></el-date-picker>-->
<!--          </el-form-item>-->
<!--        </el-form>-->
<!--        <div id="onlineCharts" :style="{width: '100%', height: '400px'}"></div>-->
<!--      </div>-->
    </div>
  </basic-container>
</template>
<script>
import * as echarts from 'echarts';
import { createEventHandler } from "@/util/events";
import {
  commitAndOnline,
  submitted,
  typeAndNumber,
  typeAndNumberAudit,
  numberAndRate,
  online
} from '@/api/creativeReport/basicsReport';
import store from "@/store/"
import Moment from "moment"
import {findObjectList} from "@/util/util";
import {geActiveAndStop} from "../../api/business/offer";

export default {
  name: 'basicsReport',
  data() {
    return {
      offerList: [],
      pickerMinDate: '',//第一次选中的时间
      now:'',
      lastWeek:'',
      submitForm: {
        date: [],
      },
      submitTypeForm: {
        date: '',
        userId:['']
      },
      onLineForm: {
        date: '',
        userId: ['']
      },
      offerId: '',
      submittedList: [],
      pickerOption: { //时间范围限制
        onPick: ({ maxDate, minDate }) => {
          this.choiceDate0 = minDate.getTime();
          if (maxDate) {
            this.choiceDate0 = '';
          }
        },
        disabledDate:
          (time) => {
            const newDate = new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1;
            /*if (this.choiceDate0) {
              let choiceDateTime = new Date(this.choiceDate0).getTime();
              const minTime = new Date(choiceDateTime).setMonth(new Date(choiceDateTime).getMonth() - 1);
              const maxTime = new Date(choiceDateTime).setMonth(new Date(choiceDateTime).getMonth() + 1);
              const min = minTime;
              const max = newDate < maxTime ? newDate : maxTime;
              return time.getTime() < min || time.getTime() > max;
            }*/
            return time.getTime() > newDate;
          }
      },
    }
  },
  beforeRouteLeave(to, form, next) {
    let self = this;
    if(self.eventHandler) {
      self.eventHandler.clear();
    }
    next();
  },
  created() {
    geActiveAndStop(store.state.user.user_id).then(res => {
      this.offerList = res.data.data
      this.offerList.unshift({name: '全部', id: ''})
    })
    this.offerId = store.state.user.offer
    this.refresh = ()=>{
      //refresh开始，这样写避免代码迁移太多

    submitted(this.offerId).then(res => {
      this.submittedList = [{id:'',realName:'全部'},...res.data.data]
    })
    this.$nextTick(() => {
      this.init()
    })
    this.lastWeek = Moment().subtract('days', 6).format('yyyy-MM-DD')
    this.now = Moment().format('yyyy-MM-DD')
    this.submitForm.date = [this.lastWeek , this.now]
    this.submitTypeForm.date = [this.lastWeek , this.now]
    this.onLineForm.date = [this.lastWeek , this.now]
    // this.submitTypeForm.userId = ['']
    // this.onLineForm.userId = ['']

      //refresh结束
    };

    let self = this;
    this.eventHandler = createEventHandler("offerCenter")
      .addListener((event) => {
        if(event.message == 'offerChanged' && event.offerId && event.offerId !== "" ) {
          this.offerId = event.offerId
          self.refresh();
        }
      });
    this.refresh();
  },
  methods: {
    controlOnLineUserId(val){
      if(val.findIndex(item => item === "") !== -1 &&  val.length > 1 && val[val.length-1] !== ""){
        val.splice(val.findIndex(item => item === ""), 1)
      }else if(val[val.length-1] === ""){
        val = [""]
      }
      this.onLineForm.userId = val;
      this.onlineBarStatistics();
    },
    controlSubmitUserId(val){
      if(val.findIndex(item => item === "") !== -1 &&  val.length > 1 && val[val.length-1] !== ""){
        val.splice(val.findIndex(item => item === ""), 1)
      }else if(val[val.length-1] === ""){
        val = [""]
      }
      this.submitTypeForm.userId = val
      this.initSubmitCharts();
      //
      this.barStatistics()
    },
    init() {
      this.barStatistics()
      this.initSubmitCharts();
      this.onlineBarStatistics()
    },

    //每日制作及在线数查询
    barStatistics() {
      if(this.submitForm.date == null || this.submitForm.date.length == 0) {
        return;
      }
      let data = {
        beginDate: this.submitTypeForm.date[0],
        endDate: this.submitTypeForm.date[1],
        offerId: this.offerId,
        designerIds:this.submitTypeForm.userId.join(',')
      }
      commitAndOnline(data).then(res => {
        if (res.data.success) {
          this.initBarEcharts(res.data.data.xAxis, res.data.data.yAxisCommit, res.data.data.yAxisOnline);
        }
      })
    },
    //制作素材类型及数量统计
    initSubmitCharts() {
      if(this.submitTypeForm.date == null || this.submitTypeForm.date.length == 0) {
        return;
      }
      let data = {
        beginDate: this.submitTypeForm.date[0],
        endDate: this.submitTypeForm.date[1],
        offerId: this.offerId,
        userId: this.submitTypeForm.userId.join(',')
      }
      typeAndNumber(data).then(res => {
        this.initStatisticsBar(res.data.data.xAxis,
          res.data.data.yAxisImage, res.data.data.yAxisVideo, res.data.data.mapping);
        let val = {
          userId: res.data.data.mapping[res.data.data.xAxis[0]],
          offerId: this.offerId,
          beginDate: this.submitTypeForm.date[0],
          endDate: this.submitTypeForm.date[1],
        }
        typeAndNumberAudit(val).then(res => {
          this.initStatisticsPie(res.data.data)
        })
        numberAndRate(val).then(res => {
          this.initStatisticsLine(res.data.data)
        })
      })
    },

    onlineBarStatistics() {
      if(this.onLineForm.date == null || this.onLineForm.date.length == 0) {
        return;
      }
      let data = {
        beginDate: this.onLineForm.date[0],
        endDate: this.onLineForm.date[1],
        offerId: this.offerId,
        userId: this.onLineForm.userId.join(',')
      }
      online(data).then(res =>{
        var series = []
        res.data.data.mapping.map((item,index) =>{
          let name
          if(item.image === '-1'){
              name  = '全部'
          }else{
            this.submittedList.map(i =>{
              if(i.id === item.image){
                name = i.realName
              }
            })
          }
          res.data.data.yAxisImage.map((it,i)=>{
            if(index === i){
              series.push(
                {
                  name: '图片',
                  type: 'bar',
                  stack: name,
                  label: {
                    show: true
                  },
                  data:it
                },
              )
            }

          })
          res.data.data.yAxisVideo.map((it,i)=>{
            if(index === i){
              series.push({
                name: '视频',
                type: 'bar',
                stack: name,
                label: {
                  show: true
                },
                data: it
              },)
            }
          })
        })
        this.initOnlineBarEcharts(res.data.data , series);
      })

    },

    getEchartsInst(eleName) {
      let ele = document.getElementById(eleName);
      let myInst = echarts.getInstanceByDom(ele);
      if(myInst) {
        return myInst;
      } else {
        return echarts.init(ele);
      }
    },
    //每日制作及在线数
    initBarEcharts(xAxisData, yAxisCommitData, yAxisOnlineData) {
      let myChart = this.getEchartsInst('submitNumCharts')
      let option = {
        title: {
          text: '每日提交及有花费素材'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          // data: ['每日制作', '每日在线',]
          data:['每日提交','有花费素材']
        },
        xAxis: [
          {
            type: 'category',
            data: xAxisData,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
          },
        ],
        series: [
          {
            name: '每日提交',
            type: 'bar',
            data: yAxisCommitData
          },
          {
            name: '有花费素材',
            type: 'bar',
            data: yAxisOnlineData
          },
        ]
      };
      option && myChart.setOption(option);
    },

    //在线素材
    initOnlineBarEcharts(data,series1) {
      let myChart = this.getEchartsInst('onlineCharts')
      let option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // Use axis to trigger tooltip
            type: 'shadow'        // 'shadow' as default; can also be 'line' or 'shadow'
          }
        },
        legend: {
          data: ['图片', '视频',],
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.xAxis
        },
        yAxis: {
          type: 'value'
        },
        series: series1
      };
      option && myChart.setOption(option,true);
    },

    initStatisticsBar(xAxis, yAxisImage, yAxisVideo, mapping) {
      let myChart = this.getEchartsInst('StatisticsBar')
      let option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['图片', '视频']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xAxis,
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '图片',
            type: 'bar',
            stack: 'total',
            label: {
              show: true
            },
            emphasis: {
              focus: 'series'
            },
            data: yAxisImage
          },
          {
            name: '视频',
            type: 'bar',
            stack: 'total',
            label: {
              show: true
            },
            emphasis: {
              focus: 'series'
            },
            data: yAxisVideo
          },
        ]
      };
      myChart.on('click', (param) => {
        if(!mapping[param.name]){
          return
        }
        let data = {
          userId: mapping[param.name],
          offerId: this.offerId,
          beginDate: this.submitTypeForm.date[0],
          endDate: this.submitTypeForm.date[1],
        }
        typeAndNumberAudit(data).then(res => {
          this.initStatisticsPie(res.data.data)
        })
        numberAndRate(data).then(res => {
          this.initStatisticsLine(res.data.data)
        })
      })
      option && myChart.setOption(option);
    },

    initStatisticsPie(data) {
      let myChart = this.getEchartsInst('StatisticsPie')
      let option = {
        title: {
          text: '素材审核结果',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {d}%'
        },
        series: [
          {
            name: '素材审核结果',
            type: 'pie',
            radius: '50%',
            data: [
              {value: data.videoPass, name: '视频通过率', itemStyle: {color: '#90EE90'}},
              {value: data.videoReject, name: '视频拒绝率', itemStyle: {color: '#CD5C5C'}},
              {value: data.videoNotAudit, name: '视频未审核', itemStyle: {color: '#27727B'}},
              {value: data.imagePass, name: '图片通过率', itemStyle: {color: '#6495ED'}},
              {value: data.imageReject, name: '图片拒绝率', itemStyle: {color: '#8B1A1A'}},
              {value: data.imageNotAudit, name: '图片未审核', itemStyle: {color: '#FCCE10'}},
              {value: data.other, name: '其它', itemStyle: {color: '#aaa'}}
            ],
          }
        ]
      };
      option && myChart.setOption(option);
    },

    initStatisticsLine(data, initSelected = [true,true,true]) {
      let self = this;
      self.numberAndRateData = data;
      let legendData = ['图片', '视频', '通过率'];
      let legendDataColor = ['#DAA520', '#87CEEB', '#9ACD32'];
      let myChart = this.getEchartsInst('StatisticsLine');
      if(self.numberAndRateDataOnLegendSelectChanged == null) {
        self.numberAndRateDataOnLegendSelectChanged = (params)=> {
          if(!params.selected[legendData[2]]) {
            return;
          }
          let newSelected = [];
          legendData.forEach((legendDataName)=>{
            newSelected.push(params.selected[legendDataName]);
          })
          self.$nextTick(() => {
            self.initStatisticsLine(self.numberAndRateData,newSelected);
          })
        };
        myChart.on('legendselectchanged',self.numberAndRateDataOnLegendSelectChanged);
      }
      let legendDataSelected = {};
      for(let i=0;i<legendData.length;i++) {
        legendDataSelected[legendData[i]] = initSelected[i];
      }
      let poList = data.poList;
      let imageNumber = [];
      let videoNumber = [];
      let passRate = [];
      data.xAxis.forEach(date=>{
        let countObjectList = findObjectList(poList,date,'date');
        let imageSelected = initSelected[0];
        let videoSelected = initSelected[1];
        let rateSelected = initSelected[2];

        let imageCount = 0;
        let passedImageCount = 0;
        let videoCount = 0;
        let passedVideoCount = 0;
        let passedRate = 0;

        countObjectList.forEach(countObject=>{
          if(countObject.type == 0) {
            imageCount += countObject.total;
            if(countObject.status == 2) {
              passedImageCount += countObject.total;
            }
          }
          if(countObject.type == 1) {
            videoCount += countObject.total;
            if(countObject.status == 2) {
              passedVideoCount += countObject.total;
            }
          }
        });
        if(rateSelected) {
          let passedCount = (imageSelected || videoSelected)?(((imageSelected)?passedImageCount:0) + ((videoSelected)?passedVideoCount:0)):(passedImageCount + passedVideoCount);
          let totalCount = (imageSelected || videoSelected)?(((imageSelected)?imageCount:0) + ((videoSelected)?videoCount:0)):(imageCount + videoCount);
          if(totalCount> 0) {
            let passedRateNum = Math.round(passedCount * 10000.0 / totalCount ).toString();
            while(passedRateNum.length < 3) {
              passedRateNum = '0' + passedRateNum;
            }
            passedRate = (passedRateNum.substring(0,passedRateNum.length - 2) + '.' + passedRateNum.substring(passedRateNum.length - 2)) * 1;
          }
        }
        imageNumber.push(imageCount);
        videoNumber.push(videoCount);
        passRate.push(passedRate);
      });

      let option = {
        xAxis: {
          type: 'category',
          data: data.xAxis,

        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            if(params.length == 0) {
              return '';
            }
            let showTextList = [];
            for(let n=0;n<params.length;n++) {
              let param = params[n];
              if(n > 0) {
                showTextList.push('<br>');
              }
              if(param.seriesIndex == 2) {
                showTextList.push(param.seriesName + ':' + param.value + '%');
              } else {
                showTextList.push(param.seriesName + ':' + param.value);
              }
            }
            return showTextList.join('');
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        legend: {
          data: legendData,
          boundaryGap: false,
          color: legendDataColor,
          selected: legendDataSelected,
        },
        yAxis: {
          type: 'value',

        },
        series: [
          {
            name: legendData[0],
            data: imageNumber,
            type: 'line'
          },
          {
            name: legendData[1],
            data: videoNumber,
            type: 'line'
          },
          {
            name: legendData[2],
            data: passRate,
            type: 'line'
          },
        ]
      }
      option && myChart.setOption(option);
    },
    timeChange(val, type) {
      switch (type) {
        case 'submitType':
          this.$nextTick(() => {
            this.barStatistics();
            this.initSubmitCharts();
          });
          break;
        case 'onLine':
          this.$nextTick(() => {
            this.onlineBarStatistics();
          });
          break;
      }
    },
  }
}
</script>
<style lang="scss">
.echarts-border {
  width: 90%;
  margin: 0 auto;
  margin-top: 50px;
  box-shadow: 2px 2px 19px 2px rgba(0, 0, 0, 0.18);
  border-radius: 20px;
  padding: 15px;
}
</style>
